import axios from "axios";
import { getToken, clearStore, setToken } from '../utils/token.js'
import { Message, MessageBox } from 'element-ui';

// 环境的切换
// let baseUrl = urlConfig[process.env.NODE_ENV];
let axiosApi = axios.create({
    baseURL: "/tmser"
})
// 请求超时时间
axiosApi.defaults.timeout = 15000;
axiosApi.defaults.withCredentials = true;

// 请求头
axiosApi.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';

// 请求拦截
axiosApi.interceptors.request.use(
    function (x) {
        let token = getToken();
        if (token) {
            x.headers.token = token;
        }
        return x;
    },
    function (error) {
        return Promise.reject(error);
    }
);

// 响应拦截
axiosApi.interceptors.response.use(
    function (response) {
        if (response.data.errorMsg === "unauthorized") {
            // MessageBox.alert("登录已失效，请重新登录！", "提示", {
            //     confirmButtonText: "跳转登录页面",
            //     callback: action => {
            setToken('');
            setUserInfo('');
            clearStore();
            window.location.href = '/login';
            //     }
            // });
        }
        return response;
    },
    function (error) {
        Message.error({
            message: error.response.message || error || "请求过程出现异常"
        });
        return Promise.reject(error);
    }
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const get = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        axiosApi
            .get(url, {
                params: params,
            }, config)
            .then((res) => {
                resolve(res.data)
            })
            .catch((err) => {
                reject(err)
            })
    })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
const post = (url, params, config = {}) => {
    return new Promise((resolve, reject) => {
        axiosApi
            .post(url, params, config)
            .then((res) => {
                resolve(res.data)
            })
            .catch((err) => {
                reject(err)
            })
    })
}

export {
    get,
    post
}
